<?php
/**
 * Created by PhpStorm.
 * User: liujun
 * Date: 2018/8/10
 * Time: 下午1:42
 */

require_once __DIR__."/base.php";

$lastTime = \Dai\Framework\Library\RedisExt::getInstance()->get("dump_order");
if( intval($lastTime) == 0) {
    $lastTime = time() -   (time()%86400) -86400 *2 ;
}
$endTime = time();

$lastTimeStr = date('Y-m-d H:i:s', $lastTime);
$endTimeStr = date('Y-m-d H:i:s', $endTime + 3600 * 24);


$orders = \PddWechat\Library\PddLibrary::getOrderList(1, 100, $lastTimeStr,  $endTimeStr);
//$orders = '{"success":true,"errorCode":1000000,"errorMsg":null,"result":{"debugTrace":null,"list":[{"orderSn":"1808103-0544822699350751","goodsId":1911722044,"goodsName":"单件/套装 男童夏装棉麻套装中大童装夏季儿童夏天短袖两件套夏款","goodsQuantity":1,"goodsThumbUrl":"http://t00img.yangkeduo.com/t03img/images/2018-07-05/5fe04d646b45c8f6c394a650567e2c85.jpeg","orderAmount":1290,"goodsPrice":1790,"platformDiscount":0,"duoId":1884871,"pid":"1884871_22329699","pidName":"推广A","orderCreateTime":1533879860000,"orderSettleTime":null,"promotionRate":200,"promotionAmount":258,"promotionSn":null,"orderStatus":5,"orderStatusDesc":"审核失败","verifyTime":1533889072000,"payTime":1533879866000,"groupSuccessTime":1533879866000,"confirmReceiveTime":null,"withdrawTime":null,"batchNo":"","orderType":null,"modifyAt":1533889072000,"type":1,"typeDesc":null,"groupId":482054482699350751,"groupIdStr":null,"authDuoId":0,"customParameters":"UG625","status":-1,"adId":5,"source":null,"fakeId":null}],"pageNum":1,"pageSize":20,"totalCount":1,"ready":true}}';
//$orders = json_decode($orders, true);

if( $orders['success'] !== true) {
    echo "get orderList fail, pageNum [1], pageSize [100], $lastTimeStr, $endTimeStr\n";
    exit;
}


$totalCount = $orders['result']['totalCount'];

if( $totalCount <= 0) {
    echo "get orderList null, pageNum [1], pageSize [100], $lastTimeStr, $endTimeStr\n";
    exit;
}

$list = $orders['result']['list'];

$orderData = new \PddWechat\Models\Pddorder\Data\PddOrderData();


foreach ($list as $order) {

    $pddOrder = new \PddWechat\Models\Pddorder\DataObject\PddOrderDo();
    /** @var \PddWechat\Models\Pddorder\DataObject\PddOrderDo $pddOrder */
    $pddOrder = \PddWechat\Library\ClassLibrary::classCopy($order, $pddOrder);
    /** @var \PddWechat\Models\Pddorder\DataObject\PddOrderDo $pddOrder */
    $pddOrderDo = $orderData->selectByOrderId($pddOrder->orderSn);

    if( $pddOrderDo == null) {
        echo "order not exist, " . json_encode($pddOrderDo)."\n";
        insertOrder($pddOrder);
    }else {
        echo "order has exist, " . json_encode($pddOrderDo)."\n";
        updateOrder($pddOrder, $pddOrderDo);
    }
}


/**
 * @param \PddWechat\Models\Pddorder\DataObject\PddOrderDo $pddOrderDo
 * 新增订单
 */
function insertOrder(\PddWechat\Models\Pddorder\DataObject\PddOrderDo $pddOrderDo){
    if( trim($pddOrderDo->customParameters) == "" ||  $pddOrderDo->promotionAmount <= 0) {
        return ;
    }

    $userData = new \PddWechat\Models\User\Data\UserData();
    $userDo = $userData->selectByInviteCode($pddOrderDo->customParameters);
    $inviteUserDo = null;
    $inviteParentUserDo =  null;

    //如果用户存在
    if( $userDo != null) {
        //用户 0.3的返现
        $pddOrderDo->uid = $userDo->id;
        $pddOrderDo->uidMoney = intval($pddOrderDo->promotionAmount * 0.3);

        //如果存在上级
        if( $userDo->inviteUid > 0 ) {
            $inviteUserDo = $userData->selectByUid($userDo->inviteUid);
            //如果有上级
            if( $inviteUserDo != null) {
                $pddOrderDo->inviteUid = intval($userDo->inviteUid);
                //如果上级是渠道，那么返回渠道佣金返回，个人10%
                if( $inviteUserDo->channelType == 1) {
                    $pddOrderDo->uidMoney = intval($pddOrderDo->promotionAmount * 0.1);
                    $pddOrderDo->inviteUidMoney = intval($pddOrderDo->promotionAmount * $inviteUserDo->channelRate /100);
                }else {
                    $pddOrderDo->inviteUidMoney = intval($pddOrderDo->promotionAmount * 0.2);
                }

                //发送模板
                $msg = getSendNewInviteMsg($pddOrderDo, $userDo, $inviteUserDo);
                if( strlen($inviteUserDo->openId) >15) {
                    sendOrderNewInviteTemplate($inviteUserDo,$pddOrderDo, $msg);
                }
            }

            //如果有上上级别
            if( $inviteUserDo != null && $inviteUserDo->inviteUid > 0 && $inviteUserDo->channelType == 0) {
                $inviteParentUserDo = $userData->selectByUid($inviteUserDo->inviteUid);
                //如果上上级别不是渠道
                if( $inviteParentUserDo != null && $inviteParentUserDo->channelType == 0){
                    $pddOrderDo->inviteParentUid = $inviteUserDo->inviteUid;
                    $pddOrderDo->inviteParentUidMoney = $pddOrderDo->inviteParentUid > 0 ? intval( $pddOrderDo->promotionAmount * 0.1 ) : 0;
                    //发送模板
                    $msg = getSendNewInviteMsg($pddOrderDo, $userDo, $inviteUserDo, $inviteParentUserDo);
                    sendOrderNewInviteTemplate($inviteParentUserDo,$pddOrderDo, $msg);
                }
            }
        }

        sendTemplate($userDo->id, $userDo->openId, $userDo->userName, $pddOrderDo);

        //平台奖金
        $pddOrderDo->remainMoney = $pddOrderDo->promotionAmount - $pddOrderDo->uidMoney -$pddOrderDo->inviteUidMoney - $pddOrderDo->inviteParentUidMoney;
    }else {
        $pddOrderDo->remainMoney = $pddOrderDo->promotionAmount;
    }

    global  $orderData;
    $pddOrderDo->id=null;

    $orderData->insert($pddOrderDo);
    echo "insert data " . json_encode($pddOrderDo)."\n";


    sendAdminTemplate($userDo == null ? '未知': $userDo->userName, $pddOrderDo);
}

/**
 * 给上级发送分佣push
 * @param \PddWechat\Models\User\DataObject\UserDo  $userDo
 * @param \PddWechat\Models\Pddorder\DataObject\PddOrderDo $pddOrder
 */
function sendOrderNewInviteTemplate($userDo,  $pddOrder, $msg){
    $topColor = '#7B68EE';
    $wordColor="#173177";

    $template = [
        'touser' => $userDo->openId,
        'template_id' => "79iS_ziWOji3UbUG2UC2hPRaruAzEnysM2JXWAOiCK4",
        'url' => "http://pdd.keepfoolish.cn/user_center.html",
        'topcolor' => $topColor,
    ];

    $template['data'] = [
        'first' => ['value' => $msg, 'color' => $wordColor],
        'keyword1' => ['value' => $pddOrder->goodsName, 'color' => $wordColor],
        'keyword2' => ['value' => round($pddOrder->orderAmount/100, 2)."元", 'color' => $wordColor],
        'keyword3' => ['value' => $pddOrder->orderSn, 'color' => $wordColor],
        'remark' => ['value' => "订单确认收货20天之后您就可以把钱提现到银行卡，赶紧去邀请其他好友赚钱吧", 'color' => $wordColor],
    ];
    \Dai\Framework\Library\Log::info("openId Is ".var_export($template, true));
    \PddWechat\Library\WechatLibrary::sendTemplate($userDo->id, $userDo->openId, json_encode($template, JSON_UNESCAPED_UNICODE ));
}

/**
 * 给上级发送分佣msg
 * @param \PddWechat\Models\Pddorder\DataObject\PddOrderDo $pddOrder
 * @param \PddWechat\Models\User\DataObject\UserDo  $useDo
 * @param \PddWechat\Models\User\DataObject\UserDo  $useDo1
 * @param \PddWechat\Models\User\DataObject\UserDo  $userDo2
 * @return string
 */
function getSendNewInviteMsg($pddOrder, $useDo, $useDo1, $userDo2 = null){
    $userName = $userDo2 == null ? $useDo1->userName : $userDo2->userName;
    $inviteUserName = $userDo2 == null ? $useDo->userName : $useDo1->userName."的好友".$useDo->userName;
    $inviteMoney = $userDo2 == null ? $pddOrder->inviteUidMoney : $pddOrder->inviteParentUidMoney;
    $msg = sprintf("%s, 您的好友 [%s] 下单了，您将分的该订单的推荐奖金 [%s]元. ", $userName, $inviteUserName, round($inviteMoney/100, 2));
    if( $userDo2 != null) {
        $msg .= sprintf("您的好友[%s] 本单可以拿到佣金 [%s]元", $useDo1->userName, round($pddOrder->inviteUidMoney/100, 2) );
    }
    return $msg;
}


/**
 * 给购买用户发消息
 * @param $uid
 * @param $openId
 * @param $nickName
 * @param \PddWechat\Models\Pddorder\DataObject\PddOrderDo $pddOrderDo
 */
function sendTemplate($uid, $openId, $nickName, \PddWechat\Models\Pddorder\DataObject\PddOrderDo $pddOrderDo) {
    $topColor = '#7B68EE';
    $wordColor="#173177";
    $template = [
        'touser' => $openId,
        'template_id' => "ssQwA9gUkHy75UpWCy-XWhxZN7VqFefXcI5SHVQWPEQ",
        'url' => "http://pdd.keepfoolish.cn/user_center.html",
        'topcolor' => $topColor,
    ];

    $msg = sprintf("\n%s, 恭喜你下单成功, 金额 [%s]元, 平台将返可提现现金 [%s]元, 确认收货20天后平台才会返现哦！\n\n自己购买,平台会返现;推荐好友,他下单,你可以拿到推荐佣金,他推荐的好友下单,你依然可以拿到随机奖励\n\n赶紧点击右下方'我要赚钱->邀请好友赚钱'赚钱吧", $nickName, round($pddOrderDo->orderAmount/100, 2), round($pddOrderDo->uidMoney/100, 2));

    $template['data'] = [
        "name" => ['value' => $pddOrderDo->goodsName, 'color' => $wordColor],
        'remark' => ['value' => $msg, 'color' => $wordColor],
    ];
    \Dai\Framework\Library\Log::info("openId Is ".var_export($template, true));
    \PddWechat\Library\WechatLibrary::sendTemplate($uid, $openId, json_encode($template, JSON_UNESCAPED_UNICODE ));
}



/**
 * 给管理员发消息
 * @param $nickName
 * @param \PddWechat\Models\Pddorder\DataObject\PddOrderDo $pddOrderDo
 */
function sendAdminTemplate($nickName, \PddWechat\Models\Pddorder\DataObject\PddOrderDo $pddOrderDo) {

    $adminUsers = [
//        [
//            'uid' => 1,
//            'uname' => '龙门港',
//            'openId' => 'o4DJE57LYJR0AvSN_GYp9jqgztJ4',
//        ],
        [
            'uid' => 3,
            'uname' => 'noodles',
            'openId' => 'o4DJE53uSMy8GmeoTYAIOnuap5-g',
        ],

        [
            'uid' => 4,
            'uname' => '周得军',
            'openId' => 'o4DJE5xq2S0uxCRw84vxgM6sZkuA',
        ],
    ];

    $topColor = '#7B68EE';
    $wordColor="#173177";

    //推送给管理员
    foreach ($adminUsers as $adminUser) {

        $openId =  $adminUser['openId'];
        $uid = $adminUser['uid'];
        $uname = $adminUser['uname'];

        $template = [
            'touser' => $openId,
            'template_id' => "UcwCGxwZqWAA-T8B_fcKwzXIJ-5cfyy96rOH8YvDR2U",
            'url' => "http://pdd.keepfoolish.cn/admin/order/list",
            'topcolor' => $topColor,
        ];

        $msg = sprintf("%s, 如下订单存在更新, 金额 [%s]元, Pdd佣金[%s]元, 平台佣金[%s]元,审核失败则没有佣金", $uname, round($pddOrderDo->orderAmount/100,2), round($pddOrderDo->promotionAmount/100,2),  round($pddOrderDo->remainMoney/100,2));

        $template['data'] = [
            'keyword1' => ['value' => $pddOrderDo->orderSn, 'color' => $wordColor],
            'keyword2' => ['value' => $pddOrderDo->orderStatusDesc, 'color' => $wordColor],
            'keyword3' => ['value' => $nickName, 'color' => $wordColor],
            'keyword4' => ['value' => $pddOrderDo->modifyAt, 'color' => $wordColor],
            'remark' => ['value' => $msg , 'color' => $wordColor],
        ];
        \Dai\Framework\Library\Log::info("openId Is ".var_export($template, true));
        \PddWechat\Library\WechatLibrary::sendTemplate($uid, $openId, json_encode($template, JSON_UNESCAPED_UNICODE ));
    }
}


/** 更新订单
 * @param \PddWechat\Models\Pddorder\DataObject\PddOrderDo $updatePddOrderDo
 * @param \PddWechat\Models\Pddorder\DataObject\PddOrderDo $pddOrderDo
 */
function updateOrder(\PddWechat\Models\Pddorder\DataObject\PddOrderDo $updatePddOrderDo, \PddWechat\Models\Pddorder\DataObject\PddOrderDo $pddOrderDo) {

    if( $pddOrderDo->orderStatus == $updatePddOrderDo->orderStatus) {
        return;
    }

    global $orderData;
    $userData = new \PddWechat\Models\User\Data\UserData();
    $id = $pddOrderDo->id;

    /** @var \PddWechat\Models\Pddorder\DataObject\PddOrderDo  $pddOrderDo */
    $pddOrderDo = \PddWechat\Library\ClassLibrary::classCopy($updatePddOrderDo, $pddOrderDo);
    $pddOrderDo->id = $id;
    $orderData->edit($pddOrderDo);
    $userDo = $userData->selectByInviteCode($pddOrderDo->customParameters);

    sendAdminTemplate($userDo == null ? $pddOrderDo->uid : $userDo->userName, $pddOrderDo);
}
